"use client";

import { usePathname } from "next/navigation";
import { useEffect, useState, useCallback, memo } from "react";
import Image from "next/image";
import Link from "next/link";
import { getLogoUrl, getImageUrl } from "@/lib/utils";

// 使用memo包装NavLink组件以避免不必要的重渲染
const NavLink = memo(({ href, name, isActive, onClick }: { 
  href: string; 
  name: string; 
  isActive: boolean;
  onClick?: () => void;
}) => (
  <Link 
    href={href}
    className={`relative px-4 py-2 rounded-lg text-sm font-medium transition-all duration-300 overflow-hidden ${
      isActive
        ? "text-white" 
        : "text-white/80 hover:text-white"
    }`}
    onClick={onClick}
  >
    {isActive && (
      <span className="absolute inset-0 rounded-lg transition-all duration-300 -z-10 bg-white/10"></span>
    )}
    <span className="relative z-10">{name}</span>
  </Link>
));

NavLink.displayName = 'NavLink';

export const Header = () => {
  const pathname = usePathname();
  const [scrolled, setScrolled] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [mounted, setMounted] = useState(false);
  const logoUrl = getLogoUrl();

  // 确保客户端挂载后再进行操作
  useEffect(() => {
    setMounted(true);
    
    // 使用防抖优化滚动处理
    let scrollTimer: any;
    const handleScroll = () => {
      if (!scrollTimer) {
        scrollTimer = setTimeout(() => {
          setScrolled(window.scrollY > 20);
          scrollTimer = null;
        }, 10); // 10ms的防抖时间
      }
    };

    // 立即检查一次滚动位置
    setScrolled(window.scrollY > 20);
    
    // 使用passive: true提高滚动性能
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => {
      window.removeEventListener("scroll", handleScroll);
      if (scrollTimer) clearTimeout(scrollTimer);
    };
  }, []);

  const navItems = [
    { name: "主页", href: "/" },
    { name: "博客", href: "/blog" },
    { name: "Ai导航", href: "/navigation" },
    { name: "我的简历", href: "/about" },
  ];

  // 使用useCallback优化isActive函数
  const isActive = useCallback((href: string) => {
    if (!mounted) return false;
    return pathname === href || (href !== "/" && pathname?.startsWith(href));
  }, [mounted, pathname]);

  // 预载Logo图片
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const img = new window.Image();
      img.src = getImageUrl(logoUrl);
    }
  }, [logoUrl]);

  // 处理移动菜单关闭
  const handleCloseMenu = useCallback(() => {
    setMobileMenuOpen(false);
  }, []);

  if (!mounted) {
    return (
      <header className="fixed top-0 left-0 right-0 z-50 py-4 bg-transparent backdrop-blur-md">
        <div className="container mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between rounded-xl px-4 transition-all duration-300">
            {/* 空白占位，确保布局稳定 */}
            <div className="h-8"></div>
          </div>
        </div>
      </header>
    );
  }

  return (
    <header className={`fixed top-0 left-0 right-0 z-50 transition-all duration-500 ${
      scrolled 
        ? "py-2 bg-white/15 backdrop-blur-md shadow-lg" 
        : "py-4 bg-transparent backdrop-blur-md"
    }`}>
      <div className="container mx-auto px-4 sm:px-6 lg:px-8">
        <div className={`flex items-center justify-between rounded-xl ${
          scrolled ? "px-3" : "px-4"
        } transition-all duration-300`}>
          {/* Logo */}
          <div className="flex items-center">
            <Link href="/" className="flex items-center space-x-2 group">
              <div className={`transition-all duration-500 ${scrolled ? "scale-90" : ""}`}>
                <Image 
                  src={getImageUrl(logoUrl)}
                  alt="illli Logo" 
                  width={24} 
                  height={24} 
                  className="transition-all duration-300 group-hover:rotate-6"
                  priority
                  loading="eager"
                />
              </div>
              <span className={`font-bold text-lg transition-all duration-300 ${
                scrolled 
                  ? "text-indigo-950" 
                  : "text-white"
              } group-hover:text-indigo-400`}>
                illli Ai Studio
              </span>
            </Link>
          </div>

          {/* Desktop Navigation */}
          <nav className="hidden md:flex items-center space-x-1">
            {navItems.map((item) => (
              <NavLink 
                key={item.href}
                href={item.href}
                name={item.name}
                isActive={isActive(item.href)}
              />
            ))}
          </nav>

          {/* Mobile menu button */}
          <button 
            onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
            className="md:hidden p-2 rounded-lg focus:outline-none transition-all duration-300"
            aria-expanded={mobileMenuOpen}
          >
            <svg 
              className="w-5 h-5 transition-all duration-300 text-white"
              fill="none" 
              stroke="currentColor" 
              viewBox="0 0 24 24"
            >
              <path 
                strokeLinecap="round" 
                strokeLinejoin="round" 
                strokeWidth={2} 
                d={mobileMenuOpen ? "M6 18L18 6M6 6l12 12" : "M4 6h16M4 12h16M4 18h16"} 
              />
            </svg>
          </button>
        </div>
      </div>

      {/* Mobile Navigation */}
      {mobileMenuOpen && (
        <div className="md:hidden px-4 py-3 border-t border-gray-200 bg-white/15 backdrop-blur-md">
          <nav className="flex flex-col space-y-2">
            {navItems.map((item) => (
              <NavLink 
                key={item.href}
                href={item.href}
                name={item.name}
                isActive={isActive(item.href)}
                onClick={handleCloseMenu}
              />
            ))}
          </nav>
        </div>
      )}
    </header>
  );
};
